package main
import (
	"fmt"
	"net"
	"os"
	"io"
)

func main(){
	
	/*监听127.0.0.1::8000端口*/
	listen, err := net.Listen("tcp", "192.168.0.2:8000")
	if err != nil{
		fmt.Println("Listen err : ", err)
		return
	}
	fmt.Println("Listen Tcp 192.168.0.2:8000 OK")
	
	/*接收客户端连接消息*/
	for{
		conn, err := listen.Accept()
		if err != nil{
			fmt.Println("Accept err : ", err)
			return
		}
		go jieshou(conn)
	}
}

func jieshou(conn net.Conn){
	defer conn.Close()
	/*输出连接信息*/
	fmt.Println(conn.RemoteAddr(), "连接成功")
	
	/*读取用户发送的文件名消息*/
	buf := make([]byte, 1024 * 4)
	sum, err := conn.Read(buf)
	if err != nil{
		fmt.Println("Read err : ", err)
		return
	}
	filename := string(buf[:sum])
	fmt.Println("Read : ", filename)
	
	/*读取成功后，向客户端发送OK消息*/
	sum, err = conn.Write([]byte("OK"))
	if err != nil{
		fmt.Println("Write err : ", err)
		return
	}
	f, err2 := os.Create(filename)
	if err2 != nil{
		fmt.Println("Create err : ", err2)
		return
	}
	defer f.Close()
	for{
		sum, err = conn.Read(buf)
		if err != nil{
			if err == io.EOF{
				fmt.Println("接收完毕！")
				break
			}
			fmt.Println("Read err : ", err)
			return
		}
		f.Write(buf[:sum])
	}
}